package tech.yixiyun.framework.kuafu.controller.action;


import tech.yixiyun.framework.kuafu.controller.request.KuafuRequest;
import tech.yixiyun.framework.kuafu.controller.response.KuafuResponse;

import java.util.LinkedList;

/**
 * 管理当前线程的Action
 */
public class ActionContext {

    private static final ThreadLocal<LinkedList<Action>> ACTIONS = new ThreadLocal<>();

    /**
     * 获取当前线程的action
     * @return
     */
    public static Action getAction() {

        LinkedList<Action> list = ACTIONS.get();
        return (list == null || list.isEmpty()) ? null : list.peek();
    }

    /**
     * 注册Action
     * @param action
     */
    public static void register(Action action) {
        LinkedList<Action> list = ACTIONS.get();
        if (list == null) {
            list = new LinkedList<Action>();
            ACTIONS.set(list);
        }
        list.addFirst(action);

        ActionDoneRegistry.register(() -> {
            unRegister();
        });

    }

    /**
     * 移除action
     */
    public static void unRegister() {
        LinkedList<Action> list = ACTIONS.get();
        if (list != null && list.isEmpty() == false) {
            list.removeFirst();
        }
        //线程复用，就不用remove了，防止重复实例化linkedlist。只要保证每次请求完，对应的action都remove掉就行
    }

    /**
     * 获取当前action的request
     * @return
     */
    public static KuafuRequest getRequest() {
        return getAction().getRequest();
    }

    /**
     * 获取当前action的response
     * @return
     */
    public static KuafuResponse getResponse() {
        return getAction().getResponse();
    }


}
